import pymysql as pmq
import traceback
import random

# # 建表
# cur.execute("CREATE TABLE IF NOT EXISTS  Writers(Id INT PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(25))")
#
# # 插入数据一
# cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
# cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
# cur.execute("INSERT INTO writers VALUES(1,'Jack London')")
# cur.execute("INSERT INTO writers VALUES(2,'Honore de Balzac')")


def insertDataWithRollBack(ip, user, password, dbname):
    con = pmq.connect(ip, user, password, dbname)
    cur = con.cursor()
    try:
        # 执行sql语句
        # total_tag_count = 43
        # for inx in range(1,total_tag_count + 1):
        #     sql = "INSERT INTO tag(id,tag,icon,createTime,updateTime) VALUES(%d,'tag%d','',unix_timestamp(now()),unix_timestamp(now()))" % (inx,inx)
        #     print(sql)
        #     cur.execute(sql)

        index = 0
        total_book_count = 20000
        total_tag_count = 43
        book_max_tag_count = 3
        for bookInx in range(1, total_book_count + 1):
            tags = random.sample(range(1, total_tag_count + 1), random.randint(1, book_max_tag_count))
            print("tags:%s,tagSize:%d" % (str(tags), len(tags)))
            for tagInx in range(len(tags)):
                index += 1
                sql = "INSERT INTO bookTag(id,bookId,tagId) VALUES(%d,%d,%d)" % (index, bookInx, tags[tagInx])
                print(sql)
                cur.execute(sql)

        # 提交到数据库执行
        con.commit()
    except:
        traceback.print_exc()
        # 如果发生错误则回滚
        con.rollback()


if __name__ == '__main__':
    print('-----------start----------------')
    ip = 'localhost'
    user = 'root'
    password = ''
    dbname = 'comic'
    insertDataWithRollBack(ip, user, password, dbname)

    print("------finish--------------")
